package com.handpay.nocardpay.baselibrary.pay.uniopayquick.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.pay.uniopayquick.model.bean.UnionQuickPayReqBean;
import com.handpay.nocardpay.baselibrary.pay.uniopayquick.model.bean.UnionQuickPayRespBean;
import com.handpay.nocardpay.baselibrary.pay.uniopayquick.presenter.UnionPayQuickPresenter;
import com.handpay.nocardpay.baselibrary.permission.PermissionRequest;
import com.handpay.nocardpay.baselibrary.utils.ArithUtil;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.HashMap;
import java.util.List;

import static com.handpay.nocardpay.baselibrary.permission.PermissionCode.REQUEST_CODE_SETTING;

/**
 * @author sxshi
 *         开通银联快捷
 */
public class OpenUnioQuickPayFragment extends BaseFragment implements IUniopayquickView, PermissionRequest.onPermissionRequestCallBack {


    private UnionQuickPayReqBean mQuickPayReqBean;
    private UnionQuickPayRespBean mQuickPayRespBean;

    private TextView amount, transtime;

    private AppCompatEditText et_cardno;
    private AppCompatEditText et_carddate, et_cv2, mobile;
    private AppCompatCheckBox cb_agree;
    private Button open_and_pay;
    private TextView tv_proto;
    private LinearLayout ll_carddate, ll_cvn2;

    //银联快捷
    private UnionPayQuickPresenter unionPayQuickPresenter;
    private PermissionRequest perssionRequest;
    //卡片类型
    private int cardType;

    public static OpenUnioQuickPayFragment newInstance(UnionQuickPayReqBean quickPayReqBean, UnionQuickPayRespBean quickPayRespBean) {

        Bundle args = new Bundle();
        args.putParcelable(BaseProtocolKey.QUICKPAYREQ, quickPayReqBean);
        args.putParcelable(BaseProtocolKey.QUICKPAYRSP, quickPayRespBean);
        OpenUnioQuickPayFragment fragment = new OpenUnioQuickPayFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_open_quickpay;
    }

    @Override
    public String getFragmentTitle() {
        return getString(R.string.open_quickpay);
    }

    @Override
    public void initView(View view) {
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(toolbar, true);
        amount = (TextView) view.findViewById(R.id.amount);
        transtime = (TextView) view.findViewById(R.id.transtime);
        et_cardno = (AppCompatEditText) view.findViewById(R.id.et_cardno);
        et_carddate = (AppCompatEditText) view.findViewById(R.id.et_carddate);
        et_cv2 = (AppCompatEditText) view.findViewById(R.id.et_cv2);
        mobile = (AppCompatEditText) view.findViewById(R.id.mobile);
        cb_agree = (AppCompatCheckBox) view.findViewById(R.id.cb_agree);
        open_and_pay = (Button) view.findViewById(R.id.open_and_pay);
        tv_proto = (TextView) view.findViewById(R.id.tv_proto);

        ll_carddate = (LinearLayout) view.findViewById(R.id.ll_carddate);
        ll_cvn2 = (LinearLayout) view.findViewById(R.id.ll_cvn2);
    }

    @Override
    public void initListener() {

        open_and_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                perssionRequest.requestPermission(Permission.LOCATION);
            }
        });

        cb_agree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                open_and_pay.setEnabled(isChecked);
            }
        });

        tv_proto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017-9-26 跳转到银联用户协议
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        this.mQuickPayReqBean = getArguments().getParcelable(BaseProtocolKey.QUICKPAYREQ);
        this.mQuickPayRespBean = getArguments().getParcelable(BaseProtocolKey.QUICKPAYRSP);
        HPLog.d(HPLog.SSX_TAG, mQuickPayReqBean.toString());
        HPLog.d(HPLog.SSX_TAG, mQuickPayRespBean.toString());
        this.cardType = mQuickPayRespBean.getCardType();
        double mAmount = Double.parseDouble(SecureManager.getInstance().des(mQuickPayReqBean.getAmount(), 0, null));
        amount.setText(CommonUtils.formatMoneyDouble(ArithUtil.div(mAmount, 100d)));
        transtime.setText(CommonUtils.formatDateToString(CommonUtils
                .formatStringToDate(mQuickPayRespBean.getTransTime(), "yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss"));


        String transAccount = SecureManager.getInstance().des(mQuickPayRespBean.getTransAccount(), 0, null);
        et_cardno.setText(CommonUtils.formattingCard(transAccount));
        if (cardType == NoCardPayConstant.DEBIT_CARD) {
            et_carddate.setVisibility(View.GONE);
            et_cv2.setVisibility(View.GONE);
        } else {
            ll_carddate.setVisibility(View.VISIBLE);
            ll_cvn2.setVisibility(View.VISIBLE);
            et_carddate.setVisibility(View.VISIBLE);
            et_cv2.setVisibility(View.VISIBLE);
        }

        //银联快捷
        unionPayQuickPresenter = new UnionPayQuickPresenter(_mActivity);
        unionPayQuickPresenter.setiUniopayquickView(this);

        perssionRequest = new PermissionRequest(_mActivity, this);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SETTING) {
            if (AndPermission.hasPermission(_mActivity, Permission.LOCATION)) {
                quickPay();
            }
        }
    }

    /**
     * 开通并支付
     */
    private void quickPay() {
        HashMap<String, Object> paramers = new HashMap<>();
        if (mQuickPayReqBean.isHistroyBankNo()) {
            paramers.put(BaseProtocolKey.CARDID, mQuickPayReqBean.getCardID());
            paramers.remove(BaseProtocolKey.CARDNO1);
        } else {
            paramers.put(BaseProtocolKey.CARDNO1, mQuickPayReqBean.getCardNo());
            paramers.remove(BaseProtocolKey.CARDID);
        }
        if (this.cardType == NoCardPayConstant.CREDIT_CARD) {
            String expireDate = et_carddate.getText().toString().trim();
            if (TextUtils.isEmpty(expireDate)) {
                DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.tip), _mActivity.getResources().getString(R.string.validity), true);
                return;
            }
            if (expireDate.length() != 4) {
                DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.tip), _mActivity.getResources().getString(R.string.truevalidity), true);
                return;

            }
            mQuickPayReqBean.setExpireDate(SecureManager.getInstance().des(expireDate, 1, null));

            String cvn2 = et_cv2.getText().toString().trim();
            if (TextUtils.isEmpty(cvn2)) {
                DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.tip), _mActivity.getResources().getString(R.string.safecode), true);
                return;
            }
            if (cvn2.length() != 3) {
                DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.tip), _mActivity.getResources().getString(R.string.truesafecode), true);
                return;
            }

            mQuickPayReqBean.setCvn2No(SecureManager.getInstance().des(cvn2, 1, null));

            paramers.put(BaseProtocolKey.EXPIREDATE, mQuickPayReqBean.getExpireDate());
            paramers.put(BaseProtocolKey.CVN2NO, mQuickPayReqBean.getCvn2No());
        } else {
            paramers.remove(BaseProtocolKey.EXPIREDATE);
            paramers.remove(BaseProtocolKey.CVN2NO);
        }


        String phone = mobile.getText().toString().trim();

        if (TextUtils.isEmpty(phone)) {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.tip), _mActivity.getResources().getString(R.string.cardno_mobile), true);
            return;
        }

        if (!CommonUtils.isMobileNum(phone)) {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getResources().getString(R.string.tip), _mActivity.getResources().getString(R.string.input_right_phone_tip), true);
            return;
        }

        mQuickPayReqBean.setMobile(SecureManager.getInstance().des(phone, 1, null));
        mQuickPayReqBean.setOperateType(NoCardPayConstant.OPEN_AND_PAY);//开通并支付
        paramers.put(BaseProtocolKey.OPERATETYPE, mQuickPayReqBean.getOperateType());
        paramers.put(BaseProtocolKey.MERCHANTCODE, mQuickPayReqBean.getMerchantCode());
        paramers.put(BaseProtocolKey.MERCHCLASSID, mQuickPayReqBean.getMerchClassId());
        paramers.put(BaseProtocolKey.AMOUNT, mQuickPayReqBean.getAmount());
        paramers.put(BaseProtocolKey.CHANNEL, mQuickPayReqBean.getChannel());
        paramers.put(BaseProtocolKey.KEY_ADDRESS, mQuickPayReqBean.getAddress());
        paramers.put(BaseProtocolKey.KEY_LOCATION, mQuickPayReqBean.getLocation());
        paramers.put(BaseProtocolKey.CLIENTCHANNEL, mQuickPayReqBean.getClientChannel());
        paramers.put(BaseProtocolKey.CLIENTVERSION, mQuickPayReqBean.getClientVersion());

        paramers.put(BaseProtocolKey.MOBILE, mQuickPayReqBean.getMobile());

        unionPayQuickPresenter.quickUnioPay(paramers, true);
    }

    @Override
    public void getPaymentResult(UnionQuickPayRespBean quickPayBean) {
        if (quickPayBean.getStatus() == 0) {//交易失敗
            startWithPop(TransactionResultsFailFragment.newInstance(quickPayBean));
        } else if (quickPayBean.getStatus() == 1) {//交易成功
            startWithPop(TransactionResultsSuccessFragment.newInstance(quickPayBean));
        } else if (quickPayBean.getStatus() == 2) {//未开通快捷
            String transStatus = SecureManager.getInstance().des(quickPayBean.getTransStatus(), 0, null);
            DialogUtils.showAlertDialog(_mActivity, getString(R.string.tip), transStatus, true);
        }
    }

    @Override
    public void permissionYes(List<String> permissions) {
        quickPay();
    }


    @Override
    public void permissionFail(List<String> permissions) {
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(_mActivity, permissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(OpenUnioQuickPayFragment.this, REQUEST_CODE_SETTING).show();
        }
    }
}
